import hashlib
import torque.api.xmlrpc as tax
import torque.api.bencode as bencode
import torque.settings as settings

from torque.torrent.models import Torrent

def generateSimpleName(name):
    endTokens = [
        'TELESYNC','DVDRIP','XVID','DIVX','LIMITED','HDDVD','X264',
        'HDTV','DVDRIP','ECHOS','CRUX','TC','TC','VHS','DVDR','DVD','NOTV','BLURAY',
        'ISO','BIA','AVI','MKV','DEITY','VISION','TL','SCENE','X86','X64','64BIT','OEM',
        'RTM','XBOX360','BRRIP','ORENJI','AC3','5.1','KTK','FLAWL3SS','HDRIP','REPACK',
        'DTS','BETA','BITMETV','INTERNAL','STV','PDTV','USA_XBOX360','NTSC','PAL',
        'LOL','WS','FLT','FQM','CAM','RERIP','USA','WII','READNFO','PS3']
    name = name.replace('.',' ')
    name = name.replace('-',' ')
    name = name.replace('_',' ')
    name = name.upper()
    parts = name.split(' ')
    x = 0
    index = 0
    for part in parts:
        if part in endTokens:
            index = x
            break;
        x += 1
    
    if index != 0:
        return ''.join(parts[0:index])
    else:
        return name
        
def matchSimpleName(hash,simpleName):
    try:
        torrent = Torrent.objects.get(hash = hash,simplename__contains = simpleName)
    except Torrent.DoesNotExist:
        return False
    else:
        return True
    
def getDetails(path):
    try:
        file = open(path,"rb")
    except:
        return None;
    
    bytes = file.read()
    torrentObj = bencode.bdecode(bytes)
    name = str(torrentObj['info']['name'])
    files = torrentObj['info']['files']
    hash = hashlib.sha1(bencode.bencode(bencode.bdecode(bytes)['info'])).hexdigest()
    
    fileList = []
    for file in files:
        fileList.append({'name':'/'.join(file['path']),'size':file['length']})
    
    outputObj = {'hash': hash, 'files': fileList, 'total': len(fileList), 'name': name, 'path': path.replace(settings.TORQUE['torrent_path'],'')}
    
    return outputObj

def getTorrentOwner(hash):
    try:
        User = Torrent.objects.get(hash=hash, status = 'A').user_id
    except:
        User = 'Unknown'
 
    return str(User)
    
def getFiles(hash):
    client = tax.connect()
    try:
        keys = ['files','file_progress','file_priorities']
        files = client.get_torrent_status(hash,keys)
    except:
        return []
    else:
        fileList = []
        x = 0
        for file in files['files']:
            file['progress'] = files['file_progress'][x]
            file['priority'] = files['file_priorities'][x]
            index = file['path'].rfind('.')
            file['extension'] = file['path'][index+1:]
            fileList.append(file)
            x += 1
            
        return fileList
        
def getTrackers(hash):
    client = tax.connect()
    try:
        keys = ['trackers']
        trackers = client.get_torrent_status(hash,keys)
    except:
        return []
    else:
        trackerList = []
        for tracker in trackers['trackers']:
            trackerList.append(tracker)
        
        return trackerList

def getPeers(hash):
    client = tax.connect()
    try:
        keys = ['peers']
        peers = client.get_torrent_status(hash,keys)
    except:
        return []
    else:
        peerList = []
        for peer in peers['peers']:
            peerList.append(peer)
        
        return peerList